﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using GuRenFang.Common;
using GuRenFang.Service.Entity;
using GuRenFang.Service.IBiz;

namespace GuRenFang.Controllers.Management
{
    public class HomePageController : Controller
    {
        private readonly IPhotosBiz _photosService;

        public HomePageController(IPhotosBiz photosService)
        {
            _photosService = photosService;
        }

        [Authorize]
        public ActionResult Images(int? page = 1)
        {
            ViewBag.Model = "Home";

            short size = Convert.ToInt16(ConfigurationManager.AppSettings["AdminpageSize"]);

            int totalRecord = 0;
            IEnumerable<Photos> imgs = _photosService.GetItemsByPagesForHomePage(out totalRecord,
                                                                                 pageIndex: page.GetValueOrDefault(),
                                                                                 pageSize: size);

            var item = new PageItem
                           {
                               CurrentPage = page.GetValueOrDefault(),
                               TotalRecords = totalRecord,
                               TotalPages = (totalRecord%size == 0) ? totalRecord/size : totalRecord/size + 1,
                               ControllerName = "Homepage",
                               ActionName = "Images"
                           };

            var viewModels = new Pager<Photos> {DataSource = imgs, Item = item};

            return View(viewModels);
        }

        [Authorize]
        public ActionResult UploadImages()
        {
            ViewBag.Model = "Home";
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult UploadImages(FormCollection form)
        {
            Photos item = new PictorialPhoto();
            item.IsDisplayOnHomePage = true;
            item.ImgPath = form["ImgPath"];
            item.ThumbnailPath = form["ThumbnailPath"];
            item.Title = form["Title"];
            item.Content = form["Content"];
            _photosService.Create(item);

            return RedirectToAction("Images", "HomePage");
        }

        [HttpPost]
        public ContentResult Upload(HttpPostedFileBase FileData, string folder)
        {
            folder = Server.UrlDecode(folder);
            string result = "";
            if (null != FileData)
            {
                try
                {
                    result = Path.GetFileNameWithoutExtension(FileData.FileName); //获得文件名
                    string ext = Path.GetExtension(FileData.FileName); //获得文件扩展名
                    saveFile(FileData, folder, result, ext); //保存文件
                    result = result + ext;
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string folder, string fileName, string extName)
        {
            string phyPath = Request.MapPath("~" + folder);
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                string imgPath = phyPath + fileName + extName;
                string thumbnailPath = phyPath + @"\Thumbnail\" + fileName + extName;
                postedFile.SaveAs(imgPath);
                MakeThumbnail(imgPath, thumbnailPath, 150, 150, "Cut");
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW": //指定高宽缩放（可能变形）
                    break;
                case "W": //指定宽，高按比例
                    toheight = originalImage.Height*width/originalImage.Width;
                    break;
                case "H": //指定高，宽按比例
                    towidth = originalImage.Width*height/originalImage.Height;
                    break;
                case "Cut": //指定高宽裁减（不变形）
                    if (originalImage.Width/(double) originalImage.Height > towidth/(double) toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height*towidth/toheight;
                        y = 0;
                        x = (originalImage.Width - ow)/2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width*height/towidth;
                        x = 0;
                        y = (originalImage.Height - oh)/2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            Image bitmap = new Bitmap(towidth, toheight);
            //新建一个画板
            Graphics g = Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                        new Rectangle(x, y, ow, oh),
                        GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
            }
            catch 
            {
                throw ;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }


        [Authorize]
        public ActionResult UpdateImages(int id)
        {
            ViewBag.Model = "Home";
            Photos photos = _photosService.GetById(id);
            if (photos == null)
            {
                ModelState.AddModelError("", "该图片不存在！");
                photos = new PictorialPhoto();
            }
            return View(photos);
        }

        [Authorize]
        [HttpPost]
        public ActionResult UpdateImages(FormCollection form, int id)
        {
            Photos item = new PictorialPhoto();
            item.Id = id;
            item.IsDisplayOnHomePage = true;
            item.ImgPath = form["ImgPath"];
            item.ThumbnailPath = form["ThumbnailPath"];
            item.Title = form["Title"];
            item.Content = form["Content"];
            _photosService.Update(item);

            return RedirectToAction("Images", "HomePage");
        }


        [Authorize]
        public ActionResult DeleteImages(int id, string file)
        {
            _photosService.Delete(id);
            FileInfo img = new FileInfo(Server.MapPath("~/" + file));
            if(img.Exists)
            {
                img.Delete();
            }
            FileInfo smallImg = new FileInfo(Server.MapPath("~/UpFiles/Photos/Thumbnail/" + img.Name));
            if(smallImg.Exists)
            {
                smallImg.Delete();
            }
            return RedirectToAction("Images", "HomePage");
        }

        [HttpPost]
        public ActionResult ContentUpload()
        {
            const int maxAttachSize = 2097152;
            string dateTimeString = DateTime.Now.ToString("yyyyMMdd");
            string upFolder = "~/UpFiles/News/" + dateTimeString + "/";
            string uploadPath = Server.MapPath(upFolder);
            string errorMsg = string.Empty;
            string fileMsg = string.Empty;
            string imagePath = string.Empty;
            string strFileName = string.Empty;
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
            byte[] fileContent; // 统一转换为byte数组处理
            try
            {
                if (disposition != null)
                {
                    // HTML5上传
                    fileContent = Request.BinaryRead(Request.TotalBytes);
                    strFileName = Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value; // 读取原始文件名
                }
                else
                {
                    // 初始化byte长度.
                    HttpPostedFileBase file = Request.Files["Filedata"];
                    strFileName = file.FileName;
                    fileContent = new Byte[file.ContentLength];
                    // 转换为byte类型
                    Stream stream = file.InputStream;
                    stream.Read(fileContent, 0, file.ContentLength);
                    stream.Close();
                }
                if (fileContent.Length == 0)
                {
                    errorMsg = "无数据提交";
                }
                else
                {
                    if (fileContent.Length > maxAttachSize)
                    {
                        errorMsg = "文件大小超过" + maxAttachSize + "字节";
                    }
                    else
                    {
                        // string strTimeInfo = DateTime.Now.ToString("yyyyMMddhhmmssfff");
                        //strFileName = strTimeInfo + "-" + strFileName;
                        imagePath = uploadPath + strFileName;
                        if (!Directory.Exists(uploadPath))
                        {
                            Directory.CreateDirectory(uploadPath);
                        }
                        var fs = new FileStream(imagePath, FileMode.Create, FileAccess.Write);
                        fs.Write(fileContent, 0, fileContent.Length);
                        fs.Flush();
                        fs.Close();

                        fileMsg = Url.Content(upFolder + strFileName);
                    }
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                Logger.Instance.Error(ex);
            }
            var jsonObject = new UpLoadMsg {err = errorMsg, msg = fileMsg};
            return Content(SerializationHelper.GetJson(jsonObject));
        }
    }
}
